<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>借货订单转换为出库单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
          name: 'temporary',
          value: 0
        });
        
        //你要引用的订单类型
        var loanId = Ext.create('Ext.form.field.Hidden', {
          name: 'loan_id',
          value:<%=params[:loan_id]%>
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });

        //所有供应商
        var toCustomer = Ext.create('Ext.form.field.Text', {
          fieldLabel: '客户',
          name: 'customer_name',
          anchor: '95%',
          readOnly:true
        });
        
        //所有仓库
        var fromWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '调出仓库',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'warehouse_id',
          loadingText: '搜索中...',
          anchor: '95%',
          minChars: 0,
          triggerAction:'all'
        });

        //出库日期
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '出库日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "出库日期必须选择",
          emptyText: '请选择日期...',
          anchor: '90%'
        });

        var linkman = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系人',
          name: 'linkman',
          anchor: '95%'
        });

        var phone = Ext.create('Ext.form.field.Text', {
          fieldLabel: '电话',
          name: 'phone',
          anchor: '95%'
        });

        var address = Ext.create('Ext.form.field.Text', {
          fieldLabel: '送货地址',
          name: 'delivery_address',
          anchor: '95%'
        });
        //--------------------------------------------------------------------------

        Ext.define('LoanDeliveryDetailAddModel', {
          extend : 'Ext.data.Model',
          fields : [{
              name: 'id'
            },{
              name: 'number'
            },{
              name: 'spec'
            },{
              name: 'product_name'
            }, {
              name: 'description'
            },{
              name: 'unit'
            },{
              name: 'order_quantity',
              type: 'int'
            },{
              name: 'quantity',
              mapping:'balance_quantity',
              type: 'int'
            },{
              name: 'ori_quantity',
              mapping:'balance_quantity',
              type: 'int'
            },{
              name: 'stock_quantity'
            },{
              name: 'product_id'
            },{
              name: 'description'
            }
          ]
        });
        
        //入库Grid Store
        var loanDetailsDS = Ext.create('Ext.data.Store', {
          autoDestroy : true,
          model : 'LoanDeliveryDetailAddModel',
          proxy : {
            type : 'ajax',
            url : '/loan/getLoanDetailBalanceForDelivery',
            extraParams:{'loan_id' : loanId.getValue()},
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          },
          autoLoad : true
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        //采购订单的产品的Grid
        var loanDetailsGrid = Ext.create('Ext.grid.Panel', {
          store: loanDetailsDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 190
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: true
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '可转数量',
              align: 'right',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 0
              }),
              width: 80
            },{
              header: '未出数量',//即当前还没有出库的数量
              align: 'right',
              dataIndex: 'order_quantity',
              width: 80
            },{
              header: '库存数量',
              align: 'right',
              dataIndex: 'stock_quantity',
              width: 80
            },{
              header: '备注',
              dataIndex: 'description',
              width: 115,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '100%'
              })
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          width: 935,
          height: 350,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              disabled: true,
              handler : function(){
                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, loanDetailsGrid.getStore().model);
                loanDetailsDS.insert(0, record);                
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = loanDetailsGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                loanDetailsDS.remove(records);
              }
            }]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交出库',
          iconCls: 'icon-save',
          handler: function(){
            //saveWarehousingEntry("save");
            if(deliveryFromLoanFormPanel.form.isValid()){
              
              var productsJsonStr = gridStoreToJson(loanDetailsDS,rejectKeyArray);
              if (loanDetailsDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = deliveryFromLoanFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan_delivery/transformLoanIntoDelivery',
                success : function (result,resp) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '提示',
                      msg: "借货订单转换为借货出库单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.alert('消息', Ext.JSON.decode(result.responseText).info);
                  }
                  newDeliveryFromLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newDeliveryFromLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
          text: '预备出库',
          tooltip: '暂时保存借货订单。',
          iconCls: 'temp-save',
          handler: function(){
            //首先把临时变量设置为1
            temporary.setValue(1);
            
            if(deliveryFromLoanFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(loanDetailsDS,rejectKeyArray);
              if (loanDetailsDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = deliveryFromLoanFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan_delivery/transformLoanIntoDelivery',
                success : function (result,resp) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.alert('消息','借货订单转换为出库单，操作成功！');
                  }
                  else {
                    Ext.MessageBox.alert('消息', Ext.JSON.decode(result.responseText).info);
                  }
                  newDeliveryFromLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newDeliveryFromLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newDeliveryFromLoanWin.destroy();
          }
        });
        
        var deliveryFromLoanFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '950',
          frame : true,
          //defaultType: 'textfield',
          url : '/loan_delivery/transformLoanIntoDelivery',
          method: 'GET',
          reader: Ext.create('Ext.data.reader.Json',{
            model: 'LoanOrderModel',
            root: 'root'
          }),
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toCustomer]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [fromWarehouse]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .15,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [linkman]
                }, {
                  columnWidth: .25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [phone]
                }, {
                  columnWidth: .6,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [address]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [loanDetailsGrid]
                }]
            },loanId,temporary],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        
        deliveryFromLoanFormPanel.render('delivery_form');

        loanDetailsGrid.on('edit', afterEdit, this );

        function afterEdit(editor,obj,options) {
          // execute an XHR to send/commit data to the server, in callback do (if successful):
          if(obj.field=="quantity"){
            if (obj.record.get('quantity') > obj.record.get('ori_quantity') || obj.record.get('quantity')  == 0){
              obj.record.set('quantity', obj.record.get('ori_quantity'));
              return;
            }
          }
        }

        deliveryFromLoanFormPanel.form.load({
          url: '/loan/getLoanById?id=' + <%=params[:loan_id]%>,
          method : 'GET',
          waitMsg: '正在载入数据...',
          success: function(form, action){
          },
          failure: function(form, action){
            Ext.MessageBox.alert('提示信息', '信息加载失败');
          }
        });
      })
    </script>
  </head>
  <body>
    <div id="delivery_form"></div>
  </body>
</html>
